package com.kanshu.ksgb.fastread.doudou.module.personal.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import com.kanshu.ksgb.fastread.doudou.R
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult
import com.kanshu.ksgb.fastread.doudou.common.net.retrofit.RetrofitHelper
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.RookieGift
import com.kanshu.ksgb.fastread.doudou.module.personal.bean.UpdateInfoEvent
import com.kanshu.ksgb.fastread.doudou.module.personal.presenter.PersonCenterService
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_new_gifts_activity.*
import org.greenrobot.eventbus.EventBus
import java.util.concurrent.TimeUnit

/**
 * 新手礼包
 * Created by wcy on 18/5/31.
 */
class NewGiftsActivity : BaseActivity() {
    val apiService = RetrofitHelper.getInstance().createService(PersonCenterService::class.java)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        title = "新手礼包"
        setContentView(R.layout.activity_new_gifts_activity)
        val enableMakeMoney =MMKVDefaultManager.getInstance().isEnableMakeMoneyModule
        btn_make_money.visibility = if (enableMakeMoney) View.VISIBLE else View.GONE
        lockGift()
        btn_make_money.setOnClickListener {
            finish()
            ARouterUtils.toActivity(ARouterConfig.HOME_PAGE, "tab_index", ARouterConfig.HomePageParams.TAB_MAKE_MONEY.toString())
           // startCountDown(60)
        }
        checkRookieGift()
        btn_get.setOnClickListener { getRookieGift()}
        btn_get2.setOnClickListener { getRookieGift()}
    }


   private fun checkRookieGift(){
       apiService.checkRookieGift()
               .compose(asyncRequest())
               .subscribe(object : Observer<BaseResult<RookieGift>>{
                   override fun onComplete() {
                   }

                   override fun onSubscribe(d: Disposable?) {
                   }

                   override fun onNext(t: BaseResult<RookieGift>?) {
                       val time = t?.result?.data?.receive_time?:-2
                       when(time){
                           -2L ->{
                               lockGift()
                               status.setText("接口异常")
                           }
                           -1L ->{
                               val rmbFloat= t?.result?.data?.rmb?.toFloat()?:0f
                               total_amount.text = String.format("%1$.2f",rmbFloat / 100f)
                               countDownView?.visibility = View.INVISIBLE
                               status.text = "已经领取过新手礼包，不能再领取"
                               lockGift()
                           }
                           0L -> unlockGift()
                           else-> {
                               val rmbFloat= t?.result?.data?.rmb?.toFloat()?:0f
                               total_amount.text = String.format("%1$.2f",rmbFloat / 100f)
                               status.text = "已自动存入零钱包"
                               lockGift()
                               startCountDown(time)
                           }
                       }

                   }

                   override fun onError(e: Throwable?) {
                       e?.printStackTrace()
                   }

               })
   }


    private fun unlockGift(){
        top_container.setBackgroundResource(R.mipmap.gift_unlock_bg)
        btn_get.visibility = View.VISIBLE
        btn_get2.visibility = View.VISIBLE
        countDownView.visibility = View.GONE
        total_tips.visibility = View.GONE
        incoming.visibility = View.GONE
        status.visibility = View.GONE
    }

    private fun lockGift(){
        top_container.setBackgroundResource(R.mipmap.gift_lock_bg)
        btn_get.visibility = View.GONE
        countDownView.visibility = View.VISIBLE
        total_tips.visibility = View.GONE
        incoming.visibility = View.VISIBLE
        status.visibility = View.VISIBLE
    }

    private fun startCountDown(totalLeft:Long) {
        ic_clock.visibility = View.VISIBLE
        countDownView.visibility = View.VISIBLE
        Observable.intervalRange(1, totalLeft+ 1, 0, 1, TimeUnit.SECONDS)
                .observeOn(AndroidSchedulers.mainThread())
                .takeUntil(lifeCyclerSubject)
                .subscribe(object : Observer<Long> {
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(t: Long?) {
                        updateCountDonwView(totalLeft - (t ?: 0))
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                    }

                })

    }

    private val str2W = "%1$02d"
    private val preFixCountDownStr = "下次领取时间还剩："
    private fun updateCountDonwView(secondsLeft: Long) {
        if(secondsLeft == 0L){
            unlockGift()
            return
        }
        val leftHour = secondsLeft / 3600
        val leftMin = secondsLeft  % 3600 / 60
        val leftSec = secondsLeft  % 3600 % 60 + 1
        val builder = StringBuilder(preFixCountDownStr)
        builder.append(String.format(str2W, leftHour))
        builder.append(": ")
        builder.append(String.format(str2W, leftMin))
        builder.append(": ")
        builder.append(String.format(str2W, leftSec))
        countDownView.text = builder.toString()
    }


    private fun getRookieGift(){
        apiService.rookieGift
                .compose(asyncRequest())
                .subscribe(object : Observer<BaseResult<RookieGift>>{
                    override fun onComplete() {
                    }

                    override fun onSubscribe(d: Disposable?) {
                    }

                    override fun onNext(t: BaseResult<RookieGift>?) {
                        val code = t?.result?.status?.code ?:-1
                        if(code == 0){
                            ToastUtil.showMessage("领取成功")
                        }else{
                            ToastUtil.showMessage("领取失败: ${t?.result?.status?.msg}")
                            return
                        }
                        EventBus.getDefault().post(UpdateInfoEvent())
                        val times = t?.result?.data?.times?:0
                        status.text = "已自动存入零钱包"
                        val rmbFloat= t?.result?.data?.rmb?.toFloat()?:0f
                        total_amount.text = String.format("%1$.2f",rmbFloat / 100f)
                        lockGift()
                        if(times > 0 ){
                            startCountDown(t?.result?.data?.next_time ?:0L)
                        }else{
                            countDownView.text = "恭喜~您的新手礼包已全部到账！"
                            ic_clock.visibility = View.GONE
                        }
                    }

                    override fun onError(e: Throwable?) {
                        e?.printStackTrace()
                        ToastUtil.showMessage("领取失败")
                    }

                })
    }

    companion object {
        @JvmStatic
        fun actionStart(activity: Activity){
            activity.startActivity(Intent(activity, NewGiftsActivity::class.java))
        }
    }


}
